package com.example.scaffolding.db.dao

import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.scaffolding.db.MyDataBase
import com.example.scaffolding.db.bean.User
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException

@RunWith(AndroidJUnit4::class)
class UserDaoTest() {

    private lateinit var userDao: UserDao
    private lateinit var db: MyDataBase

    @Before
    fun createDb() {
        val context = ApplicationProvider.getApplicationContext<Context>()
        db = Room.inMemoryDatabaseBuilder(context, MyDataBase::class.java).build()
        userDao = db.userDao()
    }

    @After
    @Throws(IOException::class)
    fun closeDb() {
        db.close()
    }

    @Test
    @Throws(Exception::class)
    fun writeUserAndReadInList() {
        val poly: User = User().apply {
            id = 0
            name = "Poly"
            type = 0
            url = "http://"
        }

        val mike: User = User().apply {
            id = 1
            name = "Mike"
            type = 1
            url = "http://"
        }

        userDao.insert(mike)
        userDao.insert(poly)

        val value = userDao.users

        assertFalse(value.isNullOrEmpty())
        println("size = ${value?.size}")
        assertEquals(value?.size, 2)
    }
}